<script setup lang="ts">
import { reqGetConsultOrderPre } from '@/services/consult'
import { reqGetpatientDetetail } from '@/services/user'
import { useConsultStore } from '@/stores'
import type { ConsultOrderPreData } from '@/types/consult'
import type { Patient } from '@/types/user'
import { Dialog, Toast } from 'vant'
import { onMounted, ref } from 'vue'
import { reqCreateConsultOrder } from '@/services/consult'
import { onBeforeRouteLeave, useRouter } from 'vue-router'
import CpPaySheet from '../../components/CpPaySheet.vue'

const store = useConsultStore()
// = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 预支付数据
const payInfo = ref<ConsultOrderPreData>()
// 发送请求-预支付
const loadData = async () => {
  const res = await reqGetConsultOrderPre({
    // 接口需要传type 和illness，从pinia中取
    type: store.consult.type,
    illnessType: store.consult.illnessType
  })
  // 拿到预支付的信息
  payInfo.value = res.data
  // 设置默认优惠券-存在pinia中
  store.setCoupon(payInfo.value.couponId)
  // store.setCoupon(res.data.couponId)
}

//  = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 患者详情数据
const patient = ref<Patient>()
// 发送请求-患者详情
const loadPatient = async () => {
  // 如果没有患者数据，直接返回
  if (!store.consult.patientId) return
  // 拿患者详情数据
  const res = await reqGetpatientDetetail(store.consult.patientId)
  patient.value = res.data
}

onMounted(() => {
  if (!store.consult.type) {
    return Dialog.alert({
      title: '温馨提示',
      message: '问诊信息不完整',
      closeOnPopstate: false
    })
      .then(() => {
        router.push('/')
      })
      .catch(() => {})
  }

  // 已进入页面就调用
  loadData()
  loadPatient()
})

const agree = ref(false)

// 打开抽屉
const show = ref(false)
// // 那种支付方式
// const paymentMethod = ref<0 | 1>(0)
// 支付的患者id
const orderId = ref('')
// 加载圈
const loading = ref(false)
// ============================================= 点第一个支付,通过pinia中存储的所有患者信息，发请求，拿到订单id
const submit = async () => {
  if (!agree.value) return Toast('请勾选我已同意支付协议')
  // *** 通过pinia中所有的患者信息，去拿我们的订单id
  const res = await reqCreateConsultOrder(store.consult)
  // 开启加载圈
  loading.value = true
  // *** 拿到订单id
  orderId.value = res.data.id
  // 数据回来了 关闭加载圈
  loading.value = false

  // 清除pinia中的consult
  // store.clear()
  // 打开抽屉
  show.value = true
}

const router = useRouter()
// 点击抽屉动作面板以外的其他地方触发before-close，后面跟函数，关闭前的回调函数
//    支持返回 Promise
//    返回false可阻止关闭，所以此处的逻辑是：点击继续支付就不会关闭抽屉面板，所以，应该在Dialog的.then中 => return false
//    返回true，就是点击了 仍然关闭，就会关闭抽屉动作面板
const onClose = () => {
  return Dialog.confirm({
    title: '关闭支付',
    message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    cancelButtonText: '仍要关闭',
    confirmButtonText: '继续支付',
    confirmButtonColor: 'var(--cp-primary)'
  })
    .then(() => {
      return false
    })
    .catch(() => {
      orderId.value = ''
      // console.log('router.push')
      router.push('/user/consult')
      return true
    })
}

// 很厉害的守卫，在页面中，触发router之后会触发这个函数，如果return false，就拦截在此页面
onBeforeRouteLeave(() => {
  // console.log('onBeforeRouteLeave')
  // 此处的逻辑是如果有支付订单在 禁止跳走
  if (orderId.value) return false
})

// ============================================= 点第二个支付
// const pay = async () => {
//   //判断是否选择了支付方式
//   if (paymentMethod.value === undefined) return Toast('请选择支付方式')
//   Toast.loading('跳转支付')
//   const res = await reqGetConsultOrderPayUrl({
//     orderId: orderId.value,
//     paymentMethod: paymentMethod.value,
//     payCallback: 'http://localhost:5173/room'
//   })
//   // console.log(res)
//   // 把拿回来的支地址进行跳转
//   window.location.href = res.data.payUrl
// }
</script>

<template>
  <div class="consult-pay-page" v-if="payInfo">
    <cp-nav-bar title="支付" />
    <div class="pay-info">
      <p class="tit">图文问诊 {{ payInfo?.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${payInfo.couponDeduction}`" />
      <van-cell title="积分抵扣" :value="`-¥${payInfo.pointDeduction}`" />
      <van-cell title="实付款" :value="`¥${payInfo.actualPayment}`" class="pay-price" />
    </van-cell-group>
    <div class="pay-space"></div>
    <van-cell-group>
      <van-cell
        title="患者信息"
        :value="`${patient?.name} | ${patient?.genderValue} | ${patient?.age}岁`"
      ></van-cell>
      <van-cell title="病情描述" :label="store.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="agree">我已同意 <span class="text">支付协议</span></van-checkbox>
    </div>
    <van-submit-bar
      button-type="primary"
      :price="payInfo.actualPayment * 100"
      button-text="立即支付"
      text-align="left"
      :loading="loading"
      @click="submit"
    />
    <!-- close-on-popstate 是否在页面回退时自动关闭 -->
    <!-- closeable 是否显示关闭图标 -->
    <!-- before-close 关闭前的回调函数，返回false可阻止关闭，支持返回 Promise -->

    <!-- 抽离公共组件 -->
    <cp-pay-sheet
      v-model:show="show"
      :actual-payment="payInfo.actualPayment"
      :order-id="orderId"
      :before-close="onClose"
      :pay-callback="`/room`"
    ></cp-pay-sheet>

    <!-- <van-action-sheet
      v-model:show="show"
      title="选择支付方式"
      :close-on-popstate="false"
      :closeable="false"
      :before-close="onClose"
    >
      <div class="pay-type">
        <p class="amount">￥{{ payInfo.actualPayment.toFixed(2) }}</p>
        <van-cell-group>
          <van-cell title="微信支付" @click="paymentMethod = 0">
            <template #icon><cp-icon name="consult-wechat" /></template>
            <template #extra><van-checkbox :checked="paymentMethod === 0" /></template>
          </van-cell>
          <van-cell title="支付宝支付" @click="paymentMethod = 1">
            <template #icon><cp-icon name="consult-alipay" /></template>
            <template #extra><van-checkbox :checked="paymentMethod === 1" /></template>
          </van-cell>
        </van-cell-group>
        <div class="btn">
          <van-button type="primary" round block @click="pay">立即支付</van-button>
        </div>
      </div>
    </van-action-sheet> -->
  </div>
</template>

<style lang="scss" scoped>
.pay-type {
  .amount {
    padding: 20px;
    text-align: center;
    font-size: 16px;
    font-weight: bold;
  }
  .btn {
    padding: 15px;
  }
  .van-cell {
    align-items: center;
    .cp-icon {
      margin-right: 10px;
      font-size: 18px;
    }
    .van-checkbox :deep(.van-checkbox__icon) {
      font-size: 16px;
    }
  }
}

::v-deep() {
  .van-submit-bar__button {
    font-weight: normal;
    width: 160px;
  }
}

.pay-schema {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  .text {
    color: var(--cp-primary);
  }
}

.pay-price {
  ::v-deep() {
    .vam-cell__title {
      font-size: 16px;
    }
    .van-cell__value {
      font-size: 16px;
      color: var(--cp-price);
    }
  }
}
.pay-space {
  height: 12px;
  background-color: var(--cp-bg);
}

.pay-info {
  display: flex;
  padding: 15px;
  flex-wrap: wrap;
  align-items: center;
  .tit {
    width: 100%;
    font-size: 16px;
    margin-bottom: 10px;
  }
  .img {
    margin-right: 10px;
    width: 38px;
    height: 38px;
    border-radius: 4px;
    overflow: hidden;
  }
  .desc {
    flex: 1;
    > span {
      display: block;
      color: var(--cp-tag);
      &:first-child {
        font-size: 16px;
        color: var(--cp-text2);
      }
    }
  }
}

.consult-pay-page {
  padding: 46px 0 50px 0;
}
</style>
